package com.copsoftware.reportes.geografico.support;

import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;
import java.util.List;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.copsoftware.reportes.geografico.beans.BeanIntervalDate;
import com.copsoftware.utils.beans.DateFormatter;
import com.copsoftware.utils.beans.DateUtils;

public class BeanIntervalDatesBuilder {
	
	protected final Log logger = LogFactory.getLog(getClass());
	
	long daysBetween;

	long numInterv;

	long daysPerInterval;

	Date feInicial;

	Date feFinal;

	List listaInterval;

	public BeanIntervalDatesBuilder(String fechaInicial, String fechaFinal,
			String numIntervalos) {
		super();
		feInicial = DateFormatter.parse(fechaInicial);
		feFinal = DateFormatter.parse(fechaFinal);
		daysBetween = DateUtils.daysBetween(feInicial, feFinal);
		numInterv = new Long(numIntervalos);
		daysPerInterval = daysBetween / numInterv;
		listaInterval = new ArrayList();
	}

	public List process() {

		Date lastDate = feInicial;
		for (int i = 0; i < numInterv; i++) {
			BeanIntervalDate bnIntervalDate = null;
			if (numInterv == 1)
				bnIntervalDate = new BeanIntervalDate(feInicial, feFinal);
			else {
				if (i + 1 < numInterv) {
					Date newDate = DateUtils.calculateNewDate(lastDate,
							daysPerInterval);
					bnIntervalDate = new BeanIntervalDate(lastDate, newDate);
					lastDate = DateUtils.calculateNewDate(newDate, 1);
				} else {
					bnIntervalDate = new BeanIntervalDate(lastDate, feFinal);
				}
			}
			listaInterval.add(bnIntervalDate);
			logger.info(bnIntervalDate.toString()+"\n");
		}
		logger.info("La lista de intervalos contiene "+ listaInterval.size());
		return listaInterval;
	}
	
	public static void main (String []args)
	{
		BeanIntervalDatesBuilder bnBeanIntervalDatesBuilder = 
			new BeanIntervalDatesBuilder("19/12/2007","19/01/2008","3");
		List listaDateIntervals = bnBeanIntervalDatesBuilder.process();
		for (Iterator iter = listaDateIntervals.iterator(); iter.hasNext();) {
			BeanIntervalDate element = (BeanIntervalDate) iter.next();
			System.out.println(element.getFechaInicial()+" ");
			System.out.println(element.getFechaFinal()+"\n");			
		}
	}

}
